#!/bin/bash

# 服务管理脚本
APP_NAME="barrel-fine-report"
PID_FILE="/var/run/todo-sync.pid"
JAR_FILE_NAME="todo-sync.jar"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
START_SCRIPT="/projs/todo/backend/todo-sync-start.sh"
STOP_SCRIPT="/projs/todo/backend/todo-sync-stop.sh"

case "$1" in
    start)
        echo "启动 $APP_NAME 服务..."
        $START_SCRIPT
        ;;
    stop)
        echo "停止 $APP_NAME 服务..."
        $STOP_SCRIPT
        ;;
    restart)
        echo "重启 $APP_NAME 服务..."
        $STOP_SCRIPT
        sleep 3
        $START_SCRIPT
        ;;
    status)
        if [ -f "$PID_FILE" ]; then
            PID=$(cat "$PID_FILE")
            if ps -p "$PID" > /dev/null 2>&1; then
                echo "$APP_NAME 正在运行 (PID: $PID)"
                exit 0
            else
                echo "$APP_NAME PID 文件存在但进程未运行"
                exit 1
            fi
        else
            # 检查是否有通过其他方式启动的进程
            PROCESSES=$(ps aux | grep "$JAR_FILE_NAME" | grep -v grep)
            if [ -n "$PROCESSES" ]; then
                echo "$APP_NAME 在运行但没有 PID 文件:"
                echo "$PROCESSES"
                exit 0
            else
                echo "$APP_NAME 未运行"
                exit 3
            fi
        fi
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

